<template>
  <div>
      <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>用户管理</span>
            </div>
          </template>

          <!--有权限才显示-->  
          <el-button type="primary" icon="Plus" @click="add" v-if="userErAdd">添加</el-button>


          <el-table :data="tableData" style="width: 100%" >
              <el-table-column label="序号" width="180" type="index"/>
              <el-table-column prop="account" label="账号" width="180" />
              <el-table-column prop="name" label="姓名" width="180" />
              <el-table-column prop="createTime" label="创建时间" width="200" />

              <el-table-column prop="caozuo" label="操作">
                      <!--具名插槽-->
                      <template #default="caozuo">
                          <!--把表格的主键传递过去-->
                          <el-button type="primary" icon="Setting" @click="fenPeiRole(caozuo.row.id)" v-if="userErFp">分配角色</el-button>
                      </template>
              </el-table-column>
          </el-table>

        
        </el-card>


         <!--点击新增按钮弹出对话框-->
         <el-dialog
              v-model="dialogVisible"
              title="添加"
              width="30%"
              :before-close="handleClose"
          >
           <el-form :model="addBean">
              <el-form-item label="账号" >
                <el-input  label-width="80%" v-model="addBean.account"/>
              </el-form-item>
              <el-form-item label="姓名" >
                <el-input  label-width="80%" v-model="addBean.name"/>
              </el-form-item>
              <el-form-item label="密码" >
                <el-input  label-width="80%" v-model="addBean.password"/>
              </el-form-item>
            </el-form>

              <!--底部插槽-->
              <template #footer>
              <span class="dialog-footer">
                  <el-button @click="dialogVisible = false">取消</el-button>
                  <el-button type="primary" @click="insert">确定</el-button>
              </span>
              </template>
          </el-dialog>

          <!--弹出分配角色对话框--> 
          <el-dialog
              v-model="dialogRole"
              title="分配角色"
              width="30%"
              :before-close="handleClose"
          >
          <el-form :model="setBean">
             <el-form-item label="用户id">
              <el-input  label-width="80%" v-model="setBean.userId" disabled/>
             </el-form-item>

             <el-form-item label="角色" >
                <el-select
                    v-model="roleIds"
                    multiple
                    clearable
                    collapse-tags
                    placeholder=""
                    popper-class="custom-header"
                    :max-collapse-tags="1"
                    
                  >
                    <template #header>
                      <el-checkbox
                        v-model="checkAll"
                        :indeterminate="indeterminate"
                        @change="handleCheckAll"
                      >
                        All
                      </el-checkbox>
                    </template>
                    <el-option
                      v-for="item in cities"
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id"
                    />
                  </el-select>

              </el-form-item>
              
            </el-form>

              <!--底部插槽-->
              <template #footer>
              <span class="dialog-footer">
                  <el-button @click="dialogRole = false">取消</el-button>
                  <el-button type="primary" @click="updateRole">确定</el-button>
              </span>
              </template>
          </el-dialog>

       
  </div>
</template>

<script setup lang="ts">
import {ref,onMounted,reactive,watch} from 'vue'
//引入后端接口
import {getUserList,addUser,getRoleList,setUserRole,getUserRoleIds,getMyAuth} from '@/api/index'
import type { CheckboxValueType } from 'element-plus'
//引入提示
import { ElMessage } from 'element-plus'





//表格数据
let tableData=ref([]);

//获取分页数据
let getData=async ()=>{
  //必须异步阻塞去获取 否则拿到的就是一个Promise对象
  let res=await getUserList();
  tableData.value=res.data;
}

//--------------------------按钮显示隐藏----------------------------
//添加按钮默认不显示
let userErFp=ref(false);
//分配角色按钮默认不显示
let userErAdd=ref(false);

let getAuthData= async()=>{
  //获取菜单权限
  let res=await getMyAuth();
  //如果存在对应的权限 才显示按钮
  if(res.data.indexOf('user:er:add')!==-1){
    userErAdd.value=true;
  }
  if(res.data.indexOf('user:er:fp')!==-1){
    userErFp.value=true;
  }
  
}

//加载时调用
onMounted(()=>{
  //调用查询
  getData();
  //调用权限
  getAuthData();
  
})


//添加对象
let addBean=reactive({
    name:'',
    account:'',
    password:''
})
//默认不显示对话框
let dialogVisible=ref(false)
//添加显示对话框
let add=()=>{
    //显示对话框
    dialogVisible.value=true;
    
    //把输入框显示的内容清空
    addBean.name='';
    addBean.account='';
    addBean.password='';
}

//添加用户 调用后端接口
let insert= async ()=>{
    //调用后端添加品牌方法
    let res=await addUser(addBean);
    console.log(res);
    if(res.code=='200'){
      //执行成功后关闭对话框
      dialogVisible.value=false;
      ElMessage.success('添加成功')
      //调用查询刷新界面
      getData();
    }else{
      //弹窗错误消息
      ElMessage.error(res.msg);
    }
}

//角色信息
const cities = ref([])
//全选
const checkAll = ref(false)
//监听值的变化
const indeterminate = ref(false)
//角色id 集合
const roleIds = ref<CheckboxValueType[]>([])
//分配角色对象
let setBean=reactive({
    userId:'',
    roleIds:[]
})
//默认不显示分配角色对话框
let dialogRole=ref(false)
//显示分配角色对话框
let fenPeiRole= async(id)=>{
    //显示对话框
    dialogRole.value=true;
    //获取后台角色列表接口
    let res=await getRoleList();
    cities.value=res.data;
    //赋值用户id 
    setBean.userId=id;
    //获取已经分配过的角色id
    let response=await getUserRoleIds({
      userId:id
    });
    //把已分配过的角色id数组,给roleIds赋值 使得下拉框默认选中
    roleIds.value=response.data;
}



// //添加用户 调用后端接口
let updateRole= async ()=>{
  //把角色id集合赋值 给后台对象
  setBean.roleIds=roleIds.value;
  //调用后端分配角色方法
  let res=await setUserRole(setBean);
  console.log(res);
  if(res.code=='200'){
    //执行成功后关闭对话框
    dialogRole.value=false;
    ElMessage.success('分配成功')
    //调用查询刷新界面
    getData();
  }else{
    //弹窗错误消息
    ElMessage.error(res.msg);
  }
}

//监听下拉框发生的变化
watch(roleIds, (val) => {

  if (val.length === 0) {
    checkAll.value = false
    indeterminate.value = false
  } else if (val.length === cities.value.length) {
    checkAll.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
})

//点击All 方法
const handleCheckAll = (val: CheckboxValueType) => {
  indeterminate.value = false
  if (val) {
    roleIds.value = cities.value.map((_) => _.id)
  } else {
    roleIds.value = []
  }
}

</script>

<style lang="scss">
.custom-header {
  .el-checkbox {
    display: flex;
    height: unset;
  }
}
</style>